package com.service.serviceImpl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mapper.EpisodeMapper;
import com.mapper.PlayRecordMapper;
import com.mapper.VideoMapper;
import com.mapper.VideoOrderMapper;
import com.model.Video;
import com.model.VideoOrder;
import com.service.VideoOrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * 订单服务的实现接口
 */
@Service
public class VideoOrderServiceImpl extends ServiceImpl<VideoOrderMapper, VideoOrder> implements VideoOrderService {


    @Autowired
    private VideoMapper videoMapper;

    @Autowired
    private EpisodeMapper episodeMapper;

    @Autowired
    private PlayRecordMapper playRecordMapper;


    @Override
    public VideoOrder saveOrder(int videoId,int userId) {

        //判断是否已经购买过
        VideoOrder videoOrder=getOne(Wrappers.<VideoOrder>query()
                .eq("user_id",userId)
                .eq("video_id",videoId)
                .eq("state",1)
        );
        if(videoOrder!=null) {
            return null;
        }else {
            //video是订单的视频id所对应的视频
            Video video=videoMapper.selectById(videoId);
            //新订单实体
            VideoOrder newVideoOrder=new VideoOrder();
            //订单对应的详细信息
            newVideoOrder.setUserId(userId);
            newVideoOrder.setVideoId(videoId);
            newVideoOrder.setCreateTime(new Date());
            newVideoOrder.setOutTradeNo(UUID.randomUUID().toString());
            newVideoOrder.setState(1);
            newVideoOrder.setTotalFee(video.getPrice());
            newVideoOrder.setVideoImg(video.getCoverImg());
            newVideoOrder.setVideoTitle(video.getTitle());
            //往数据库插入订单并返回
            return save(newVideoOrder)?newVideoOrder:null;

        }
    }

    @Override
    public List<VideoOrder> findOrdersByUserId(int userId) {
        return list(Wrappers.<VideoOrder>query().eq("user_id",userId).orderByDesc("create_time"));
    }

    @Override
    public VideoOrder findOrderByOutTradeNo(String outTradeNo) {
        return getOne(Wrappers.<VideoOrder>query().eq("out_trade_no",outTradeNo));
    }



}
